package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.dto.GoalDTO;
import com.xuedongzhilian.entity.Goal;
import com.xuedongzhilian.service.IGoalService;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 目标管理控制器
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/goal")
public class GoalController {

    @Resource
    private IGoalService goalService;

    /**
     * 创建目标
     */
    @PostMapping
    public Result createGoal(@RequestBody GoalDTO goalDTO) {
        Goal goal = new Goal();
        BeanUtils.copyProperties(goalDTO, goal);
        goal.setUserId(UserHolder.getUser().getId());
        goal.setStatus(1); // 进行中状态
        goal.setProgress(java.math.BigDecimal.ZERO);
        goal.setCreateTime(LocalDateTime.now());
        goal.setUpdateTime(LocalDateTime.now());
        
        boolean success = goalService.save(goal);
        if (success) {
            return Result.ok(goal);
        } else {
            return Result.fail("创建失败");
        }
    }

    /**
     * 获取用户目标列表
     */
    @GetMapping
    public Result getGoals(@RequestParam(required = false) Integer status,
                          @RequestParam(required = false) Integer type) {
        Long userId = UserHolder.getUser().getId();
        
        List<Goal> goals = goalService.lambdaQuery()
                .eq(Goal::getUserId, userId)
                .eq(status != null, Goal::getStatus, status)
                .eq(type != null, Goal::getType, type)
                .orderByDesc(Goal::getCreateTime)
                .list();
                
        return Result.ok(goals);
    }

    /**
     * 更新目标进度
     */
    @PutMapping("/progress/{id}")
    public Result updateGoalProgress(@PathVariable Long id, @RequestParam java.math.BigDecimal progress) {
        Long userId = UserHolder.getUser().getId();
        Goal goal = goalService.getById(id);
        
        if (goal == null) {
            return Result.fail("目标不存在");
        }
        
        if (!goal.getUserId().equals(userId)) {
            return Result.fail("无权操作该目标");
        }
        
        goal.setProgress(progress);
        goal.setUpdateTime(LocalDateTime.now());
        
        // 如果进度达到100%，自动标记为已完成
        if (progress.compareTo(new java.math.BigDecimal("100")) >= 0) {
            goal.setStatus(2); // 已完成状态
        }
        
        boolean success = goalService.updateById(goal);
        if (success) {
            return Result.ok(goal);
        } else {
            return Result.fail("更新进度失败");
        }
    }

    /**
     * 完成目标
     */
    @PostMapping("/complete/{id}")
    public Result completeGoal(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        Goal goal = goalService.getById(id);
        
        if (goal == null) {
            return Result.fail("目标不存在");
        }
        
        if (!goal.getUserId().equals(userId)) {
            return Result.fail("无权操作该目标");
        }
        
        if (goal.getStatus() == 2) {
            return Result.fail("目标已完成");
        }
        
        if (goal.getStatus() == 3) {
            return Result.fail("目标已放弃");
        }
        
        goal.setStatus(2); // 已完成状态
        goal.setProgress(new java.math.BigDecimal("100"));
        goal.setUpdateTime(LocalDateTime.now());
        
        boolean success = goalService.updateById(goal);
        if (success) {
            return Result.ok("目标完成");
        } else {
            return Result.fail("完成目标失败");
        }
    }

    /**
     * 放弃目标
     */
    @PostMapping("/abandon/{id}")
    public Result abandonGoal(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        Goal goal = goalService.getById(id);
        
        if (goal == null) {
            return Result.fail("目标不存在");
        }
        
        if (!goal.getUserId().equals(userId)) {
            return Result.fail("无权操作该目标");
        }
        
        if (goal.getStatus() == 2) {
            return Result.fail("目标已完成，无法放弃");
        }
        
        if (goal.getStatus() == 3) {
            return Result.fail("目标已放弃");
        }
        
        goal.setStatus(3); // 已放弃状态
        goal.setUpdateTime(LocalDateTime.now());
        
        boolean success = goalService.updateById(goal);
        if (success) {
            return Result.ok("目标已放弃");
        } else {
            return Result.fail("放弃目标失败");
        }
    }

    /**
     * 删除目标
     */
    @DeleteMapping("/{id}")
    public Result deleteGoal(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        Goal goal = goalService.getById(id);
        
        if (goal == null) {
            return Result.fail("目标不存在");
        }
        
        if (!goal.getUserId().equals(userId)) {
            return Result.fail("无权操作该目标");
        }
        
        boolean success = goalService.removeById(id);
        if (success) {
            return Result.ok("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }

    /**
     * 获取进行中的长期目标
     */
    @GetMapping("/long-term")
    public Result getLongTermGoals() {
        Long userId = UserHolder.getUser().getId();
        
        List<Goal> goals = goalService.lambdaQuery()
                .eq(Goal::getUserId, userId)
                .eq(Goal::getType, 1) // 长期目标
                .eq(Goal::getStatus, 1) // 进行中状态
                .orderByDesc(Goal::getCreateTime)
                .list();
                
        return Result.ok(goals);
    }
}